package com.app.view;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.util.TypedValue;

public class ScreenUtils {
    private static int screenW = -1;
    private static int screenH = -1;
    private static float screenDensity = -1;
    private static ScreenUtils utils;
    private ScreenUtils(){

    }
//    public static ScreenUtils getInstance(){
//        if (utils == null){
//            utils = new ScreenUtils();
//        }
//        return utils;
//    }
    public static ScreenUtils initScreen(Activity mActivity) {

        if (utils == null){

            DisplayMetrics metric = new DisplayMetrics();
            mActivity.getWindowManager().getDefaultDisplay().getMetrics(metric);
            screenW = metric.widthPixels;
            screenH = metric.heightPixels;
            screenDensity = metric.density;
            utils = new ScreenUtils();
        }
        return utils;
    }

    public static int getScreenW() {
        return screenW;
    }

    public static int getScreenH() {
        return screenH;
    }

    public float getScreenDensity() {
        return screenDensity;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public int dp2px(float dpValue) {
        return (int) (dpValue * getScreenDensity() + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public int px2dp(float pxValue) {
        return (int) (pxValue / getScreenDensity() + 0.5f);
    }

    /**
     * 根据手机的分辨率从 dip(像素) 的单位 转成为 px
     */
    public int dip2px(float pxValue) {
        return (int) (pxValue * getScreenDensity() + 0.5f);
    }

    public int dpToPx(Resources res, int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                res.getDisplayMetrics());
    }

    public int spToPx(Resources res, int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, dp,
                res.getDisplayMetrics());
    }

    /**
     * convert px to its equivalent sp
     *
     * 将px转换为sp
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    public String getScreenInfo() {
        return "getScreenH() * getScreenW()=" + getScreenH() + " * " + getScreenW();
    }

    public int getTextHeight(Paint paint,String text){
        Rect rect = new Rect();
        paint.getTextBounds(text, 0, text.length(), rect);
        return rect.height();
    }

    public int getTextWidth(Paint paint, String text){
        Rect rect = new Rect();
        paint.getTextBounds(text, 0, text.length(), rect);
        return rect.width();
    }
}